package com.sptpc.demo.controller;


import com.sptpc.demo.controller.requests.ModifyCategoryRequest;
import com.sptpc.demo.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo.model.Category;
import com.sptpc.demo.model.Drink;
import com.sptpc.demo.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    public ICategoryService categoryService;

    @GetMapping("/")
    public List<Category> getAll(){

        return categoryService.getAllCategories();
    }
//    新增
    @PostMapping("/")
    public Category addNewCategory(@RequestBody @Valid Category category,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        } else {
            log.info("创建新饮品: {}", category);
            //后期使用数据库insert
            categoryService.addNewCategory(category);
            return category;
        }
    }



    /*
  修改
 */
    @PutMapping("/")
    public Category modifyCategory(@RequestBody Category request){
        log.info("要修改的分类: {}", request);
        //1.通过查询id出分类
        Category category= categoryService.getCategoryById(request.getId());
        BeanUtils.copyProperties(request,category);
        // 3.更新数据库
        categoryService.updateCategory(category);
        return category;
    }
/*
    删除
            */
    @DeleteMapping("/{id}")
    public String deleteCategory(@PathVariable Integer id){
        log.info("要删除的饮品的id: {}",id);
        categoryService.deleteCategoryById(id);
        return "删除成功";
    }
}
